package com.org.javabody.ReflectApi;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class Private_Reflect {

	private String name = "明明";
		
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@SuppressWarnings("unused")
	private String pri_name(String name)
	{
		return name;
	}
	
	@SuppressWarnings("unused")
	private void getMessage() {
		System.out.println("打破封装");
	}


	public static void main(String[] args) throws Exception {
		 Class<?> cl = Class.forName("ReflectApi.Private_Reflect");
		 Object object = cl.newInstance();  //获取无参构造

		 
		 //访问封装的私有方法（有参）


		 Method method = cl.getDeclaredMethod("pri_name", new Class[] { String.class });//获取特定的方法用getDeclaredMethod

		 method.setAccessible(true); // 抑制Java的访问控制检查(必须加这个才能打破封装的私有方法!!!!!!)

		 String str = (String) method.invoke(object, new Object[] { "静静" });
		 System.out.println(str);
		 
		 //访问封装的私有方法(无参)


		 Method method2 = cl.getDeclaredMethod("getMessage", new Class[]{});//获取特定的方法用getDeclaredMethod

		 method2.setAccessible(true); // 抑制Java的访问控制检查(必须加这个才能打破封装的私有方法!!!!!!)

		 method2.invoke(object, new Object[]{});
		 
		 //修改封装的私有变量


		 Field field = cl.getDeclaredField("name");//获取特定的变量用getDeclaredField

		 field.setAccessible(true); // 抑制Java对修饰符的检查

		 Private_Reflect re = new Private_Reflect();
		 field.set(re, "蘑菇");	 
		 System.out.println(re.getName());
	}
}
